const { default: axios } = require("axios");
const areas = require("./new_area_code_2024.json");
const fs = require("fs");
const { v4 } = require("uuid");

const newAreas = areas.map((ele) => {
  return {
    id: v4(),
    ...ele,
  };
});
const newSortTreeArea = newAreas.sort((a, b) => a.level - b.level);
fs.writeFileSync("./newSortTreeArea.json", JSON.stringify(newSortTreeArea));

const len = newSortTreeArea.length;
let index = 0;

fs.writeFileSync(
  "./has_parents_trees_areas.json",
  JSON.stringify(newSortTreeArea)
);

console.log(len)

// return;
// return;
function requestTask() {
  const data = newSortTreeArea[index];

  if (data.pCode !== 0) {
    // save
    axios
      .get("http://localhost:7001/web-server-api/area/infoByCode", {
        params: { code: String(data.pCode) },
      })
      .then((r) => {
        console.log(String(data.pCode));
        const parent = r.data.data;
        save({ ...data, parent: parent });
      })
      .catch((err) => {
        fs.appendFileSync(
          "./log_error.json",
          JSON.stringify({
            data: data,
            error: err,
          })
        );
      });
  } else {
    save(data);
  }
}

function save(data) {
  console.log("当前区域->", data.name);
  console.log(
    "当前区域父级区域",
    data.parent ? data.parent.name : "没有父级区域"
  );
  console.log("当前父级编码", data.parent ? data.parent.code : "没有父级区域");
  axios
    .post("http://localhost:7001/un-server-api/area/save", {
      ...data,
      code: String(data.code),
      pCode: String(data.pCode),
    })
    .then((r) => {
      console.log("currentCode->", data.code);
      console.log("saveSuccess->", r.data.success);
      console.log("save Index ->", index + 1);
      if (r.data.success) {
        index++;
        if (index < len) {
          setTimeout(() => {
            console.log("等待->1S");
            requestTask();
          }, 1000);
        }
      } else {
        fs.appendFileSync(
          "./log_error.json",
          JSON.stringify({
            data: data,
            error: r.data,
          })
        );
        if (index < len) {
          setTimeout(() => {
            console.log("等待->1S");
            requestTask();
          }, 1000);
        }
      }
    })
    .catch((error) => {
      console.log("currentCode->", data.code);
      console.log(error);
      fs.appendFileSync(
        "./log_error.json",
        JSON.stringify({
          data: data,
          error: error,
        })
      );

      if (index < len) {
        setTimeout(() => {
          console.log("等待->1S");
          requestTask();
        }, 1000);
      }
    });
}

requestTask();
